// 试卷生成相关的组合式函数
import { ref, computed } from 'vue'
import { nextTick } from 'vue'

export function useExamGeneration() {
  // 响应式数据
  const examData = ref(null)
  const isGenerating = ref(false)
  const isStreaming = ref(false)
  const streamingContent = ref('')
  const currentStreamingExam = ref(null)

  // 计算属性
  const currentExamData = computed(() => {
    return currentStreamingExam.value || examData.value
  })

  const totalQuestions = computed(() => {
    const data = currentExamData.value
    if (!data) return 0
    return data.questions ? data.questions.length : 0
  })

  const choiceQuestions = computed(() => {
    return getQuestionsByType('选择题')
  })

  const fillQuestions = computed(() => {
    return getQuestionsByType('填空题')
  })

  const answerQuestions = computed(() => {
    return getQuestionsByType('解答题')
  })

  // 方法
  const getQuestionsByType = (type) => {
    const data = currentExamData.value
    if (!data?.questions) return []
    return data.questions.filter(q => q.type === type)
  }

  const getScore = (type) => {
    return SCORE_MAP[type] || 5
  }

  // 流式生成试卷
  const generateExam = async (config) => {
    console.log('开始生成试卷...')
    
    // 设置状态
    isGenerating.value = true
    isStreaming.value = true
    streamingContent.value = ''
    examData.value = null
    currentStreamingExam.value = {
      grade: config.grade,
      difficulty: config.difficulty,
      subject: config.subject,
      questions: []
    }

    try {
      const questions = []
      
      for (const [typeKey, typeConfig] of Object.entries(config.questionTypes)) {
        if (typeConfig.enabled && typeConfig.count > 0) {
          const typeMap = {
            choice: '选择题',
            fill: '填空题', 
            answer: '解答题'
          }
          
          const response = await generateQuestionsByTypeStreaming(
            typeMap[typeKey], 
            typeConfig.count,
            config
          )
          
          console.log(`${typeMap[typeKey]}生成结果:`, response)
          
          if (response && response.questions) {
            console.log(`添加${response.questions.length}道${typeMap[typeKey]}`)
            questions.push(...response.questions)
          } else {
            console.warn(`${typeMap[typeKey]}生成失败或无题目`)
          }
        }
      }
      
      examData.value = {
        grade: config.grade,
        difficulty: config.difficulty,
        subject: config.subject,
        questions: questions
      }
      
    } catch (error) {
      console.error('生成试卷失败:', error)
      throw error
    } finally {
      isGenerating.value = false
      isStreaming.value = false
    }
  }

  // 按类型生成题目（流式模式）
  const generateQuestionsByTypeStreaming = async (questionType, count, config) => {
    return new Promise((resolve, reject) => {
      streamWithFetch(questionType, count, config, resolve, reject)
    })
  }

  // 使用fetch实现流式请求
  const streamWithFetch = async (questionType, count, config, resolve, reject) => {
    try {
      const response = await fetch('/api/generate/stream', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'text/event-stream',
        },
        body: JSON.stringify({
          grade: config.grade,
          difficulty: config.difficulty,
          subject: config.subject,
          knowledge_points: config.knowledgePoints,
          question_type: questionType,
          num_questions: count
        })
      })
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }
      
      const reader = response.body.getReader()
      const decoder = new TextDecoder()
      let buffer = ''
      let finalResult = null
      
      while (true) {
        const { done, value } = await reader.read()
        
        if (done) break
        
        buffer += decoder.decode(value, { stream: true })
        const lines = buffer.split('\n')
        buffer = lines.pop()
        
        for (const line of lines) {
          let processedLine = line.trim()
          
          if (!processedLine || processedLine.startsWith(':')) continue
          
          processedLine = processedLine.replace(/^(data:\s*)+/, '')
          if (!processedLine.trim()) continue
          
          try {
            const data = JSON.parse(processedLine)
            
            if (data.type === 'start') {
              if (streamingContent.value && !streamingContent.value.endsWith('\n')) {
                streamingContent.value += '\n\n' + '='.repeat(50) + '\n\n'
              }
              streamingContent.value += `🚀 ${data.message}\n`
            } else if (data.type === 'token') {
              streamingContent.value += data.content
              tryParseStreamingContent()
              nextTick(() => {
                const examPreview = document.querySelector('.exam-preview')
                if (examPreview) {
                  examPreview.scrollTop = examPreview.scrollHeight
                }
              })
            } else if (data.type === 'success') {
              finalResult = data.data
              streamingContent.value += '\n✅ 生成完成！\n'
              
              // 累积更新 currentStreamingExam 的题目
              if (finalResult && finalResult.questions && Array.isArray(finalResult.questions)) {
                if (!currentStreamingExam.value) {
                  currentStreamingExam.value = {
                    grade: finalResult.grade || config.grade,
                    difficulty: finalResult.difficulty || config.difficulty,
                    subject: finalResult.subject || config.subject,
                    questions: []
                  }
                }
                // 累积添加题目，而不是覆盖
                currentStreamingExam.value.questions.push(...finalResult.questions)
              }
            } else if (data.type === 'done') {
              streamingContent.value += `🎉 ${data.message}\n`
              break
            } else if (data.type === 'error') {
              streamingContent.value += `❌ 错误: ${data.message}\n`
              reject(new Error(data.message))
              return
            }
          } catch (e) {
            console.warn('解析SSE数据失败:', e)
          }
        }
      }
      
      const result = finalResult || { questions: [] }
      resolve(result)
    } catch (error) {
      streamingContent.value += `❌ 网络错误: ${error.message}\n`
      reject(error)
    }
  }

  // 尝试实时解析流式内容
  const tryParseStreamingContent = () => {
    try {
      const content = streamingContent.value
      const jsonStart = content.lastIndexOf('{')
      
      if (jsonStart === -1) return
      
      let braceCount = 0
      let jsonEnd = -1
      
      for (let i = jsonStart; i < content.length; i++) {
        if (content[i] === '{') braceCount++
        else if (content[i] === '}') {
          braceCount--
          if (braceCount === 0) {
            jsonEnd = i + 1
            break
          }
        }
      }
      
      if (jsonEnd === -1) return
      
      const jsonContent = content.slice(jsonStart, jsonEnd)
      const parsed = JSON.parse(jsonContent)
      
      if (parsed && parsed.questions && Array.isArray(parsed.questions)) {
        if (!currentStreamingExam.value) {
          currentStreamingExam.value = {
            grade: parsed.grade || examData.value?.grade,
            difficulty: parsed.difficulty || examData.value?.difficulty,
            subject: parsed.subject || examData.value?.subject,
            questions: []
          }
        }
        
        const existingCount = currentStreamingExam.value.questions.length
        if (parsed.questions.length > existingCount) {
          currentStreamingExam.value.questions = [...parsed.questions]
        }
      }
    } catch (e) {
      // 静默失败，等待更多内容
    }
  }

  const clearExamData = () => {
    examData.value = null
    currentStreamingExam.value = null
    streamingContent.value = ''
  }

  return {
    examData,
    isGenerating,
    isStreaming,
    streamingContent,
    currentStreamingExam,
    currentExamData,
    totalQuestions,
    choiceQuestions,
    fillQuestions,
    answerQuestions,
    generateExam,
    getQuestionsByType,
    getScore,
    clearExamData
  }
}